package a05_双指针法;

/**
 * <p>
 * a06_删除链表的倒数第N个节点
 * </p>
 *
 * @author flyduck
 * @since 2024-07-18
 */
public class a06_删除链表的倒数第N个节点复习1 {
    //1 -> 2 -> 3-> 4 -> 5   2
    //        slow
    //                     fast
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode slowNode = dummyNode;
        ListNode fastNode = dummyNode;
        while (n + 1 > 0) {
            fastNode = fastNode.next;
            n--;
        }

        while (fastNode != null) {
            slowNode = slowNode.next;
            fastNode = fastNode.next;
        }

        slowNode.next = slowNode.next.next;
        return dummyNode.next;

    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = removeNthFromEnd(head, 2);
        System.out.println(listNode);
    }
}
